import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * This class runs the Doctor's Office's Server.
 * 
 * @author Joshua Harris
 * @version 1.0
 */
public class Server {
	
    /** 
     * maximum concurrent connections 
     */
    public static final int MAX_CONNECTIONS = 8;

    /** 
     * our thread pool 
     */
    private ExecutorService pool;

    /** 
     * the port to run on 
     */
    private int port;

    /**
     * Constructor for the class
     *
     * @param port  the port to run on
     */
    public Server(final int port) {
        this.port = port;
        pool = Executors.newFixedThreadPool(MAX_CONNECTIONS);
    }

    /**
     * Main method, just run an instance
     * of the multi server
     *
     * @param args command line not used
     */
    public static void main(final String[] args) {
        Server serv = new Server(45678);
        serv.run();
    }

    /**
     * In the run method, we loop forever accepting client connections
     * and handling them.  This time, we make a thread instead of just
     * directly handling them.
     */
    public void run() {
        ServerSocket serverSocket;
        Socket clientSocket = null;

        try {
            System.out.println("Doctor's Office Coming Online...");
            serverSocket = new ServerSocket(port);

            while (true) {
                clientSocket = serverSocket.accept();

                ServerMessageHandler handle = new ServerMessageHandler(clientSocket);
                pool.execute(handle);
            }
        } catch (IOException e) {
            System.err.println("Doctors Office - Connection Error");
            e.printStackTrace();
        }
    }
}
